package com.tianji.promotion.service.impl;

import com.tianji.promotion.constants.PromotionConstants;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.promotion.constants.PromotionConstants.COUPON_RANGE_KEY;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-02-09
 */
@Service
@RequiredArgsConstructor
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {

    private final StringRedisTemplate redisTemplate;
    private final BoundValueOperations<String, String> serialOps;

    /**
     * 异步生成兑换码
     * @param coupon
     */
    @Override
    @Async("generateExchangeCodeExecutor")
    public void asyncgenerateExchangeCode(Coupon coupon) {
        //1.调用incrby  批量生成兑换码
        //生成自增id 借助redis  incr
        Integer totalNum = coupon.getTotalNum();
        Long increment = redisTemplate.opsForValue().increment(PromotionConstants.COUPON_CODE_SERIAL_KEY, totalNum);
        if (increment==null){
            return;
        }

        int maxSerialNum = increment.intValue();//本地自增id最大值
        int begin = maxSerialNum - totalNum +1; //自增id  循环开始值
        List<ExchangeCode> list = new ArrayList<>(totalNum);
        //2.循环生成兑换码  调用工具类生成兑换码
        for (int SerialNum = begin; SerialNum<=increment; SerialNum++){
            String code = CodeUtil.generateCode(SerialNum, coupon.getId()); //参数1：自增id值 参数2：优惠券id（内部会计算出0-15的数字，找到对应的密钥）
            ExchangeCode exchangeCode = new ExchangeCode();
            exchangeCode.setCode(code);
            exchangeCode.setId(SerialNum);//兑换码id
            exchangeCode.setExchangeTargetId(coupon.getId());
            exchangeCode.setExpiredTime(coupon.getIssueEndTime());
            list.add(exchangeCode);
        }

        //3.将兑换码保存db  exchange_code  批量保存
        saveBatch(list);

        // 4.写入Redis缓存，member：couponId，score：兑换码的最大序列号
        redisTemplate.opsForZSet().add(COUPON_RANGE_KEY, coupon.getId().toString(), maxSerialNum);
    }


    @Override
    public boolean updateExchangeCodeMark(long serialNum, boolean flag) {
        String key = PromotionConstants.COUPON_CODE_MAP_KEY;
        //修改兑换码的自增id  对应offset值
        Boolean aBoolean = redisTemplate.opsForValue().setBit(key, serialNum, flag);
        return aBoolean != null && aBoolean;
    }
}
